'use strict'

const db = require('./db')
let _id = 1;

class IdsDao {
    constructor() {}
    createIdsTable() {
        let self = this
        db.ids.find({
            _id: _id
        }, function (err, docs) {
            if (!err) {
                if (!docs || docs.length === 0) {
                    let data = {
                        _id: _id,
                        userId: 0,
                        playerId: 0,
                        serverId: 0,
                        postsId: 0,
                        mailId: 0,
                        tradeId: 0,
                    }
                    db.ids.insert(data)
                } else if (!docs || docs.length === 1) {
                    let data = {
                        userId: docs[0].userId || 0,
                        playerId: docs[0].playerId || 0,
                        postsId: docs[0].postsId || 0,
                        serverId: docs[0].serverId || 0,
                        mailId: docs[0].mailId || 0,
                        tradeId: docs[0].tradeId || 0,
                    }
                    db.ids.update({
                        _id: _id
                    }, data, {
                        multi: true
                    }, function (err, numReplaced) {
                        if (err) {
                            throw new Error('ids数据出错')
                        }
                    })
                }
            }
        });
    }
    findOneAndUpdate(fieldname, callback) {
        db.ids.update({
            _id: _id
        }, {
            $inc: {
                [fieldname]: 1
            }
        }, {
            upsert: true,
            returnUpdatedDocs: true
        }, callback)
    }
}
let idsDao = new IdsDao()
module.exports = idsDao